<template>
  <Layout :user="user" :on-logout="handleLogout">
    <div class="super-admin-dashboard-container">
    <div class="dashboard-header">
      <h2>超级管理员仪表盘</h2>
      <p>欢迎回来，{{ userName }}</p>
    </div>
    
    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ totalUsers }}</div>
            <div class="stat-label">用户总数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon><Setting /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ totalAdmins }}</div>
            <div class="stat-label">管理员总数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon><Lock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ pendingApproval }}</div>
            <div class="stat-label">待审核用户</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon><Cpu /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ systemStatus }}</div>
            <div class="stat-label">系统状态</div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>用户角色分布</span>
          </div>
        </template>
        <div class="chart-content">
          <div id="userRoleChart" style="width: 100%; height: 300px;"></div>
        </div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>系统访问统计 (近7天)</span>
          </div>
        </template>
        <div class="chart-content">
          <div id="accessChart" style="width: 100%; height: 300px;"></div>
        </div>
      </el-card>
    </div>
    
    <!-- 最近系统日志 -->
    <div class="recent-logs">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>最近系统日志</span>
          </div>
        </template>
        <el-table :data="recentLogs" style="width: 100%">
          <el-table-column prop="id" label="日志ID" width="80" />
          <el-table-column prop="action" label="操作" />
          <el-table-column prop="user" label="操作用户" width="120" />
          <el-table-column prop="ip" label="IP地址" width="120" />
          <el-table-column prop="result" label="结果" width="100">
            <template #default="scope">
              <el-tag :type="getResultTagType(scope.row.result)">{{ getResultText(scope.row.result) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="操作时间" width="180" />
        </el-table>
      </el-card>
    </div>
      </div>
    </Layout>
  </template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useAuthStore } from '../../stores/auth'
import Layout from '../../components/common/Layout.vue'
import { User, Setting, Lock, Cpu } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '../../utils/request'
import { useRouter } from 'vue-router'

// 使用auth store
const authStore = useAuthStore()
const router = useRouter()

// 用户名
const userName = computed(() => authStore.userInfo?.name || '未知用户')

// Layout组件需要的user props
const user = computed(() => ({
  name: authStore.userInfo?.name || '未知用户',
  role: authStore.userInfo?.role || 'superadmin',
  phone: authStore.userInfo?.phone || undefined,
  district: undefined // 根据实际情况设置
}))

// Layout组件需要的onLogout回调
const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// 统计数据
// 类型定义
interface SystemLog {
  id: string;
  action: string;
  user: string;
  ip: string;
  result: string;
  createTime: string;
}

interface UserRoleStat {
  role_name: string;
  count: number;
}

interface AccessStat {
  date: string;
  count: number;
}

// 统计数据
const totalUsers = ref(0)
const totalAdmins = ref(0)
const pendingApproval = ref(0)
const systemStatus = ref('')
const activeUsers = ref(0)
const systemLogsCount = ref(0)

// 最近系统日志
const recentLogs = ref<SystemLog[]>([])

// 图表数据
const userRoleStats = ref<UserRoleStat[]>([])
const accessStats = ref<AccessStat[]>([])

// 图表实例
let userRoleChart: any = null
let accessChart: any = null

// 加载状态
const loading = ref(false)

// 获取结果标签类型
const getResultTagType = (result: string): string => {
  const resultMap: Record<string, string> = {
    'success': 'success',
    'failed': 'danger',
    'pending': 'warning',
    'info': 'info'
  }
  return resultMap[result] || 'info'
}

// 获取结果文本
const getResultText = (result: string): string => {
  const resultMap: Record<string, string> = {
    'success': '成功',
    'failed': '失败',
    'pending': '待处理',
    'info': '信息'
  }
  return resultMap[result] || result
}

// 初始化用户角色分布图表
const initUserRoleChart = () => {
  const chartDom = document.getElementById('userRoleChart')
  if (!chartDom) return
  
  userRoleChart = echarts.init(chartDom)
  
  // 准备数据
  const roleData = userRoleStats.value.map((item: any) => ({
    value: item.count,
    name: item.role_name
  }))
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '用户角色',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: roleData
      }
    ]
  }
  
  userRoleChart.setOption(option)
}

// 初始化系统访问统计图表
const initAccessChart = () => {
  const chartDom = document.getElementById('accessChart')
  if (!chartDom) return
  
  accessChart = echarts.init(chartDom)
  
  // 准备数据
  const dates = accessStats.value.map((item: any) => item.date)
  const counts = accessStats.value.map((item: any) => item.count)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '访问次数',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: counts
      }
    ]
  }
  
  accessChart.setOption(option)
}

// 窗口大小改变时重新渲染图表
const handleResize = () => {
  userRoleChart?.resize()
  accessChart?.resize()
}

// 提供备用数据
const provideBackupData = () => {
  // 设置默认统计数据
  totalUsers.value = 120
  totalAdmins.value = 12
  pendingApproval.value = 5
  systemStatus.value = '正常'
  activeUsers.value = 85
  systemLogsCount.value = 250
  
  // 设置默认日志数据
  recentLogs.value = [
    { id: 'L001', action: '用户登录', user: 'admin', ip: '192.168.1.100', result: 'success', createTime: '2025-09-04 08:00' },
    { id: 'L002', action: '修改系统设置', user: 'superadmin', ip: '192.168.1.101', result: 'success', createTime: '2025-09-04 09:15' },
    { id: 'L003', action: '创建管理员账号', user: 'superadmin', ip: '192.168.1.101', result: 'success', createTime: '2025-09-04 10:30' },
    { id: 'L004', action: '用户注册', user: 'newuser', ip: '192.168.1.102', result: 'pending', createTime: '2025-09-04 13:45' },
    { id: 'L005', action: '用户登录失败', user: 'user1', ip: '192.168.1.103', result: 'failed', createTime: '2025-09-04 15:20' }
  ]
  
  // 设置默认图表数据
  userRoleStats.value = [
    { role_name: '守卫', count: 85 },
    { role_name: '普通用户', count: 30 },
    { role_name: '管理员', count: 10 },
    { role_name: '超级管理员', count: 2 },
    { role_name: '待审核', count: 5 }
  ]
  
  accessStats.value = [
    { date: '8/29', count: 180 },
    { date: '8/30', count: 230 },
    { date: '8/31', count: 190 },
    { date: '9/1', count: 250 },
    { date: '9/2', count: 210 },
    { date: '9/3', count: 280 },
    { date: '9/4', count: 240 }
  ]
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    loading.value = true
    
    // 获取统计数据
    const statsData = await request.get('/api/super-admin/dashboard/stats')
    totalUsers.value = statsData.totalUsers || 0
    totalAdmins.value = statsData.totalAdmins || 0
    pendingApproval.value = statsData.pendingApproval || 0
    systemStatus.value = statsData.systemStatus || '正常'
    activeUsers.value = statsData.activeUsers || 0
    systemLogsCount.value = statsData.systemLogsCount || 0
    
    // 获取最近系统日志
    const logsData = await request.get('/api/super-admin/dashboard/logs/recent')
    recentLogs.value = logsData || []
    
    // 获取用户角色统计图表数据
    const userRoleData = await request.get('/api/super-admin/dashboard/users/role/stats')
    userRoleStats.value = userRoleData || []
    
    // 获取系统访问统计图表数据
    const accessStatsData = await request.get('/api/super-admin/dashboard/system/access/stats')
    accessStats.value = accessStatsData || []
    
    // 初始化图表
    initUserRoleChart()
    initAccessChart()
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    // 提供备用数据
    provideBackupData()
  } finally {
    loading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 加载数据
  fetchDashboardData()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  userRoleChart?.dispose()
  accessChart?.dispose()
})
</script>

<style scoped>
.super-admin-dashboard-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  background-color: #ffffff;
  min-height: 100vh;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h2 {
  font-size: 24px;
  margin: 0 0 8px 0;
  color: #333;
}

.dashboard-header p {
  color: #666;
  margin: 0;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #fff0f6;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #eb2f96;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

/* 图表容器 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  height: 350px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-content {
  height: calc(100% - 50px);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 最近日志 */
.recent-logs {
  margin-bottom: 24px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr 1fr;
  }
  
  .dashboard-header h2 {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .chart-card {
    height: 250px;
  }
}
</style>